package com.ai.util;

import com.alibaba.druid.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;

public class PingUtil {

    // 判断网络状态
    public static String isConnect(String ipAddress) throws Exception {
        BufferedReader br = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("ping " + ipAddress);
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "GB2312");
            br = new BufferedReader(inputStreamReader);
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            if (!sb.toString().contains("平均")) {
                return "无网络";
            } else {
                return sb.toString().substring(sb.toString().lastIndexOf("平均") + 5, sb.length());
            }
        } catch (Exception e) {
            throw new Exception();
        } finally {
            if (br != null) {
                br.close();
            }
        }
    }

    public static boolean ping(String ipAddress) {
        if (StringUtils.isEmpty(ipAddress)) {
            return false;
        }
        int timeOut = 3000; //超时应该在3钞以上
        boolean status; // 当返回值是true时，说明host是可用的，false则不可。
        try {
            status = InetAddress.getByName(ipAddress).isReachable(timeOut);
        } catch (IOException e) {
            return false;
        }
        return status;
    }

    public static void main(String[] args) throws Exception {
//        for (int i = 0; i < 10; i++) {
//            Thread.sleep(10000);
            System.out.println(ping("192.168.8.153"));
//        }
    }
}
